<template>
  <div class="seat-page">
    <div v-if="loading" class="loading">
      加载中...
    </div>
    <template v-else>
      <div class="header">
        <div class="back" @click="$router.back()">
          <i class="iconfont">&#xe697;</i> 返回
        </div>
        <div class="movie-info">
          <h2>{{ movie.name }}</h2>
          <p>{{ showtime.startTime }} {{ showtime.language }}{{ showtime.dimension }}</p>
        </div>
      </div>

      <div class="seat-container">
        <div class="screen">银幕</div>
        
        <div class="seat-area">
          <div class="row-indicators">
            <div v-for="row in rows" :key="row" class="row-number">{{ row }}</div>
          </div>
          
          <div class="seats-wrapper">
            <div 
              v-for="(row, rowIndex) in seatMap" 
              :key="rowIndex"
              class="seat-row"
            >
              <div 
                v-for="(seat, colIndex) in row" 
                :key="colIndex"
                :class="[
                  'seat',
                  {
                    'occupied': seat === 1,
                    'selected': isSelected(rowIndex, colIndex),
                    'available': seat === 0
                  }
                ]"
                @click="toggleSeat(rowIndex, colIndex)"
              ></div>
            </div>
          </div>
        </div>

        <div class="legend">
          <div class="legend-item">
            <div class="seat available"></div>
            <span>可选</span>
          </div>
          <div class="legend-item">
            <div class="seat occupied"></div>
            <span>已售</span>
          </div>
          <div class="legend-item">
            <div class="seat selected"></div>
            <span>已选</span>
          </div>
        </div>

        <div class="action">
          <button 
            class="confirm-btn"
            :disabled="!selectedSeats.length"
            @click="confirmSelection"
          >
            确认选座
          </button>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { movieApi } from '@/api/movie'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const movie = ref({})
const showtime = ref({})
const seatMap = ref([])
const selectedSeats = ref([])
const rows = ref([])

const isSelected = (rowIndex, colIndex) => {
  return selectedSeats.value.some(
    seat => seat.row === rowIndex && seat.col === colIndex
  )
}

const toggleSeat = (rowIndex, colIndex) => {
  const seatStatus = seatMap.value[rowIndex][colIndex]
  if (seatStatus === 1) return // 已售出的座位不能选择

  const seatIndex = selectedSeats.value.findIndex(
    seat => seat.row === rowIndex && seat.col === colIndex
  )
  
  if (seatIndex > -1) {
    selectedSeats.value.splice(seatIndex, 1)
  } else {
    if (selectedSeats.value.length >= 4) {
      alert('最多只能选择4个座位')
      return
    }
    selectedSeats.value.push({ row: rowIndex, col: colIndex })
  }
}

onMounted(async () => {
  loading.value = true
  try {
    // 并行请求电影详情和场次信息
    const [movieRes, showtimeRes, seatMapRes] = await Promise.all([
      movieApi.getMovieDetail(route.params.id),
      movieApi.getShowtimeDetail(route.params.showtimeId),
      movieApi.getSeatMap(route.params.showtimeId)
    ])

    movie.value = movieRes.data
    showtime.value = showtimeRes.data
    seatMap.value = seatMapRes.data
    
    // 生成座位行标识
    rows.value = Array.from(
      { length: seatMap.value.length }, 
      (_, i) => String.fromCharCode(65 + i)
    )
  } catch (error) {
    console.error('获取座位数据失败:', error)
    ElMessage.error('获取座位数据失败，请重试')
  } finally {
    loading.value = false
  }
})

const generateOrderNo = () => {
  const timestamp = new Date().getTime();
  const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
  return `ORDER${timestamp}${random}`;
}

const confirmSelection = async () => {
  if (!selectedSeats.value.length) {
    ElMessage.warning('请至少选择一个座位')
    return
  }
  
  try {
    loading.value = true
    
    // 检查用户登录状态
    console.log('localStorage中的userId:', localStorage.getItem('userId'))
    console.log('localStorage所有内容:', { ...localStorage })
    
    const userId = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).id : null
    if (!userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    const seatInfo = selectedSeats.value.map(seat => ({
      row: String.fromCharCode(65 + seat.row),
      col: seat.col + 1
    }))

    const orderData = {
      userId: userId,
      movieId: route.query.movieId,
      cinemaId: route.query.cinemaId,
      hallId: route.query.hallId,
      scheduleId: route.query.scheduleId,
      seatInfo: JSON.stringify(seatInfo),
      totalAmount: showtime.value.price * selectedSeats.value.length,
      orderNo: generateOrderNo(),
      ticketCount: selectedSeats.value.length
    }

    console.log('订单数据:', orderData)

    // 检查所有必需的数据
    const requiredFields = ['userId', 'movieId', 'cinemaId', 'hallId', 'scheduleId', 'seatInfo', 'totalAmount'];
    const missingFields = requiredFields.filter(field => !orderData[field]);
    
    if (missingFields.length > 0) {
      console.log('当前订单数据:', orderData); // 调试用
      throw new Error(`缺少必需的字段: ${missingFields.join(', ')}`);
    }

    const response = await axios.post(
      'http://localhost:8080/v1/order/create',
      orderData
    )

    console.log('服务器响应:', response.data)

    if (response.data && response.data.code === 2000) {
      router.push({
        path: '/payment',
        query: {
          orderNo: orderData.orderNo,
          amount: orderData.totalAmount
        }
      })
    } else {
      const errorMsg = response.data?.msg || '创建订单失败'
      console.error('订单创建失败，服务器响应:', response.data)
      throw new Error(errorMsg)
    }
  } catch (error) {
    if (error.message && error.message.includes('No match')) {
      console.error('支付页面路由错误，请检查路由配置')
      ElMessage.error('系统配置错误，请联系管理员')
    } else {
      console.error('创建订单失败:', error)
      console.error('完整错误对象:', error)
      console.error('错误响应数据:', error.response?.data)
      ElMessage.error(error.message || '创建订单失败，请重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.seat-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 60px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
}

.header {
  background: #fff;
  padding: 15px;
  margin-bottom: 20px;
}

.back {
  color: #666;
  cursor: pointer;
  margin-bottom: 10px;
}

.movie-info h2 {
  margin: 0 0 10px 0;
}

.movie-info p {
  margin: 0;
  color: #666;
}

.seat-container {
  background: #fff;
  padding: 20px;
  margin: 0 20px;
  border-radius: 8px;
}

.screen {
  background: #eee;
  text-align: center;
  padding: 10px;
  margin-bottom: 30px;
  border-radius: 4px;
  color: #666;
}

.seat-area {
  display: flex;
  margin-bottom: 30px;
}

.row-indicators {
  display: flex;
  flex-direction: column;
  margin-right: 15px;
}

.row-number {
  height: 30px;
  line-height: 30px;
  margin-bottom: 10px;
  color: #666;
}

.seats-wrapper {
  flex: 1;
}

.seat-row {
  display: flex;
  margin-bottom: 10px;
}

.seat {
  width: 30px;
  height: 30px;
  margin-right: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.seat.available {
  background: #e8f0fe;
  border: 1px solid #4285f4;
}

.seat.occupied {
  background: #eee;
  cursor: not-allowed;
}

.seat.selected {
  background: #4285f4;
}

.legend {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 30px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-item .seat {
  cursor: default;
  margin: 0;
}

.action {
  text-align: center;
}

.confirm-btn {
  padding: 12px 40px;
  background: #ff5f16;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  cursor: pointer;
}

.confirm-btn:disabled {
  background: #ffaa83;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .seat-container {
    margin: 0 10px;
    padding: 15px;
  }

  .seat {
    width: 25px;
    height: 25px;
    margin-right: 5px;
  }

  .row-number {
    height: 25px;
    line-height: 25px;
  }
}
</style> 